import { getPageListDocument, getProductInfoDocument, pushProductInfo } from '@/api/product';
import {
  getImagesFile,
  parseProductInfoDocument,
  ProductInfo,
  serializeDescription,
  uploadImage,
} from '@/lib/dianxiaomi';
import { getGigaSkuAndProductId, GigaProductInfo } from '@/lib/giga';
import { useSettingsStore } from '@/store';
import { OperationMessageType } from '@/store/message';
import { useMessage } from './useDiaoxiaomiMessage';
import { useGiga } from './useGiga';
import { usePostme } from './usePostme';

export function useProduct() {
  const pushSettings = useSettingsStore((state) => state.pushSettings);
  const accountSetting = useSettingsStore((state) => state.accountSetting);
  const { resetMessage, addMessage } = useMessage();
  const { generateProductName } = usePostme();
  const { getGigaProductInfo } = useGiga();
  const appConfig = useAppConfig();
  async function getToBePublishProductInfo() {
    const pageNo = 1;
    const pageSize = 300;
    const documents: Document[] = [];
    const productInfos: Partial<ProductInfo>[] = [];
    const document = await getPageListDocument({
      pageNo: pageNo,
      pageSize: pageSize,
    });
    // console.log(document);
    documents.push(document);
    // 获取总的条数
    const totalEle = document.querySelector<HTMLInputElement>('input[name=totalSize]');
    if (totalEle) {
      const total = Number(totalEle.value) || 0;
      // 获取所有的文档
      if (total > pageSize * pageNo) {
        const documentPromise: Promise<Document>[] = [];
        const count = Math.ceil(total / pageSize) - pageNo;
        for (let index = 0; index < count; index++) {
          documentPromise.push(
            getPageListDocument({
              pageNo: pageNo + index + 1,
              pageSize: pageSize,
            }),
          );
        }
        documents.push(...(await Promise.all(documentPromise)));
      }
    }
    documents.forEach((document) => {
      const productEles = document.querySelectorAll(
        '.in-table .content.lineContent',
      ) as NodeListOf<HTMLTableRowElement>;
      productEles.forEach((ele) => {
        const id = ele.dataset.id;
        const skuIdInfo = ele.querySelector('.in-table-in .limingcentUrlpic')?.textContent || '';
        productInfos.push({
          id: id,
          skuIdInfo: skuIdInfo,
        });
      });
    });
    return productInfos;
  }

  const replaceSettings = useCallback(
    async function replaceSettings(
      productInfo: ProductInfo,
      directoryHandle: FileSystemDirectoryHandle,
    ) {
      const productInfoFilename = appConfig.productInfoFilename;
      try {
        const fileHandle = await directoryHandle.getFileHandle(productInfoFilename, {
          create: false,
        });
        const file = await fileHandle.getFile();
        const text = await file.text();
        const productInfoSettings: ProductInfo = JSON.parse(text);
        console.log('读取的产品配置: ', productInfoSettings);
        // 替换产品的名称和英文名称
        productInfo.productName = productInfoSettings.productName;
        productInfo.productNameI18n = JSON.stringify({
          en: productInfoSettings.productName,
        });
        return productInfo;
      } catch (error) {
        console.log(error);
        throw new Error(`找不到 ${productInfoFilename} 产品信息文件: ${(error as Error).message}`);
      }
    },
    [appConfig],
  );

  const replaceImages = useCallback(
    async function replaceImages(
      productInfo: ProductInfo,
      directoryHandle: FileSystemDirectoryHandle,
      giga2bProductInfo: GigaProductInfo,
    ) {
      const imagesDirectoryname = appConfig.imagesDirectoryname;
      try {
        const imagesDirectoryHandle = await directoryHandle.getDirectoryHandle(
          imagesDirectoryname,
          {
            create: true,
          },
        );
        const imageFiles = await getImagesFile(imagesDirectoryHandle);
        addMessage({
          category: productInfo.skuIdInfo,
          type: OperationMessageType.info,
          message: `开始上传图像到服务器上(需等待一定时间)`,
        });
        const imageUrls = await Promise.all(
          imageFiles.map(async (file) => {
            const imageUrl = await uploadImage(
              file,
              productInfo,
              pushSettings.isUploadToImageSpace,
            );
            addMessage({
              category: productInfo.skuIdInfo,
              type: OperationMessageType.verbose,
              message: `${imageUrl} 图片上传到服务器上`,
            });
            return imageUrl;
          }),
        );
        addMessage({
          category: productInfo.skuIdInfo,
          type: OperationMessageType.success,
          message: `成功上传图像到服务器上`,
        });

        // 开始执行轮播图的替换
        productInfo.mainImage = imageUrls.join('|');

        // 对素材图进行替换
        productInfo.materialImgUrl = imageUrls[0] || '';

        // 替换变种属性的缩略图
        const variationListStr = productInfo.variationListStr;
        const variationListStrObj = JSON.parse(variationListStr);
        variationListStrObj.forEach((variation: any) => {
          variation.thumbUrl = imageUrls[0] || '';
        });
        productInfo.variationListStr = JSON.stringify(variationListStrObj);

        // 替换产品描述
        productInfo.description = serializeDescription(
          imageUrls,
          giga2bProductInfo.feature || [],
          giga2bProductInfo.description || [],
        );

        return productInfo;
      } catch (error) {
        console.log(error);
        throw new Error(`${(error as Error).message}`);
      }
    },
    [appConfig, pushSettings],
  );

  async function replaceAndSaveProductInfo(
    { id, skuIdInfo }: Partial<ProductInfo>,
    skuIdInfoDirectoryHandle: FileSystemDirectoryHandle,
    directoryHandle: FileSystemDirectoryHandle,
  ) {
    if (id && skuIdInfo) {
      addMessage({
        category: skuIdInfo,
        type: OperationMessageType.info,
        message: `开始进行产品的替换`,
      });

      // 读取待发布产品原来的信息
      const productDocument = await getProductInfoDocument(id);
      // console.log(productDocument);
      const [gigaSku, gigaProductId] = getGigaSkuAndProductId(skuIdInfo);
      let productInfo = parseProductInfoDocument(productDocument, {
        skuIdInfo: skuIdInfo,
        gigaSku,
        gigaProductId,
      });
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `成功获取产品的原有信息`,
      });
      console.log(productInfo.skuIdInfo, productInfo);

      // 读取产品在 gigab2b 中的信息
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.verbose,
        message: `开始获取 gigab2b 中产品的信息`,
      });
      const giga2bProductInfo = await getGigaProductInfo(productInfo);
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `成功获取 gigab2b 中产品的信息`,
      });
      console.log('gigab2b 中的产品信息', productInfo.skuIdInfo, giga2bProductInfo);

      // 标题生成
      await generateProductName(giga2bProductInfo, skuIdInfoDirectoryHandle, directoryHandle);
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `成功生成标题并保存到本地`,
      });

      // 执行配置替换
      productInfo = await replaceSettings(productInfo, skuIdInfoDirectoryHandle);
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `替换产品的名称和英文名称`,
      });

      // 执行轮播图等的替换
      productInfo = await replaceImages(productInfo, skuIdInfoDirectoryHandle, giga2bProductInfo);
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `替换产品的轮播图,素材图,变种信息预览图和产品描述`,
      });

      // 执行保存操作
      const result = await pushProductInfo(productInfo);
      if (result.code === 0) {
        console.log(productInfo);
        addMessage({
          category: productInfo.skuIdInfo,
          type: OperationMessageType.success,
          message: `产品编辑并保存成功 ${doneMessage}`,
          data: {
            kind: '产品信息',
            data: productInfo,
          },
        });
        // 继续执行后续操作
      } else {
        throw new Error(`执行保存操作失败 ${result.msgCode}: ${result.msg}`);
      }
    } else {
      throw new Error('无法获取到产品货号和 id');
    }
  }

  return {
    getToBePublishProductInfo: useCallback(getToBePublishProductInfo, [
      pushSettings,
      accountSetting,
    ]),
    replaceAndSaveProductInfo: useCallback(replaceAndSaveProductInfo, [
      getGigaProductInfo,
      generateProductName,
      replaceSettings,
      replaceImages,
      pushSettings,
      accountSetting,
    ]),
  };
}
